package com.j2205.hongzhiyuan.util;

import java.io.*;

/**
 * @ClassName MySqlBackUpUtil
 * @Description TODO
 * @Author Zbt
 * @Date 2022/8/18 14:35
 * @Version 1.0
 **/
public class MySqlBackUpUtil {
    public static String backFile = null;
    public static boolean backUp(String dbname,String path){
        String command =" mysqldump -uroot -p980121 -P3306 "+dbname ;
//        输出的文件目录 例如：D:\kejiguan.sql
        backFile = path +"\\"+dbname+System.currentTimeMillis()+".sql";
        BufferedReader reader =null;
        PrintWriter printWriter =null;
        try {
//            JVM执行一个外部指令获取该指令的执行进程（应用对象）
            Process process = Runtime.getRuntime().exec(command);
//            获取该进程的输入流
            reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
//            获取指定目录的输出流
            printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(backFile)));
            String line = null;
            while(( line = reader.readLine())!=null){
                printWriter.println(line);//按行输出字符
            }
            printWriter.flush();//清空缓冲
            if(process.waitFor()==0){
                return true;
            }

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }finally {
//关闭流资源
            try {
                printWriter.close();
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


        return false;
//        String command = " mysqldump -uroot -proot -P3306"+dbname;
//        String backFile = path+"\\"+dbname+".sql";
//        PrintWriter writer = null;
//        BufferedReader reader = null;
//        try {
//            Process process = Runtime.getRuntime().exec(command);
//            reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
//            writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(backFile)));
//            String line = null;
//            while((line = reader.readLine())!=null){
//                writer.println(line);
//            }
//            writer.flush();
//            if (process.waitFor()==0){
//                return true;
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }finally {
//            try {
//                writer.close();
//                reader.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//        return false;
    }
}
